//
//  PublicTimerDisplayView.m
//  yqApp
//
//  Created by dqb on 15/10/15.
//  Copyright © 2015年 yq. All rights reserved.
//

#import "APPublicTimerDisplayView.h"
#import "APPublicTimerDispalyCell.h"
#import "UIImageView+WebCache.h"
#import "APPageControl.h"

#define numberOfItem 3

@interface APPublicTimerDisplayView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
{
    dispatch_source_t _timer;

}
//@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableDictionary *infoDictionary;
@property (nonatomic, strong) APPageControl *pageControl;
@property (nonatomic, strong) UIImageView *bg_view;

@end

@implementation APPublicTimerDisplayView

#pragma mark -- lazyloading
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0.0f;
        layout.minimumInteritemSpacing = 0.0f;
        layout.sectionInset = UIEdgeInsetsZero;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[APPublicTimerDispalyCell class] forCellWithReuseIdentifier:@"PublicTimerDispalyCell"];
    }
    return _collectionView;
}

- (NSMutableDictionary *)infoDictionary{
    if (!_infoDictionary) {
        _infoDictionary = [NSMutableDictionary dictionary];
    }
    return _infoDictionary;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _isPageVisible = NO;
        _isAutoScroll = NO;
        _showPageBackground = NO;
        _pageControlStyle = DisplayViewPageControlStyleDefault;
        [self addSubview:self.collectionView];
        self.backgroundColor = [UIColor clearColor];
        UIImageView *bg_view = [[UIImageView alloc] init];
        bg_view.image = [UIImage imageNamed:@"buyCardDetail_overImage"];
        bg_view.hidden = YES;
        bg_view.userInteractionEnabled = YES;
        [self addSubview:bg_view];
        _bg_view = bg_view;
        
       [self addSubview:self.pageControl];
        
    }
    return self;
}

- (APPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [[APPageControl alloc] init];
        _pageControl.pageIndicatorTintColor = LYRGBColor(216, 216, 216);
        _pageControl.currentPageIndicatorTintColor = LYRGBColor(87, 61, 255);
        [_pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
        _pageControl.hidden = YES;
    }
    return _pageControl;
}


- (void)dm_setCornerRadius:(CGFloat)cornerRadius{
    self.collectionView.layer.cornerRadius = cornerRadius;
    self.collectionView.layer.masksToBounds = YES;
}

- (void)setIsAutoScroll:(BOOL)isAutoScroll{
    _isAutoScroll = isAutoScroll;
    if (isAutoScroll) {
        if (!_timer) {
            [self addTimer];
        }
    }else{
        [self removeTimer];
    }
}

- (void)setPageControlStyle:(DisplayViewPageControlStyle)pageControlStyle{
    _pageControlStyle = pageControlStyle;
    [self addSubview:self.pageControl];

}

- (void)layoutSubviews{
    [super layoutSubviews];
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    self.collectionView.frame = CGRectMake(0, 0, width, height);
    self.pageControl.frame = CGRectMake(0, height - 30, width, 30);
    self.bg_view.frame = CGRectMake(0, height - 30, width, 30);
    if (_isPageVisible) {
        self.pageControl.hidden = NO;
    }
    if (_showPageBackground) {
        self.bg_view.hidden = NO;
        self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    }
}



- (void)setUrlArray:(NSArray *)urlArray{
    _urlArray = urlArray;
    if (_isPageVisible) {
        self.pageControl.numberOfPages = urlArray.count;
    }
    if (urlArray.count >= 2) {
        if (_isAutoScroll) {
            [self addTimer];
        }
        [self.collectionView reloadData];
        [self.collectionView setContentOffset:CGPointMake(self.collectionView.bounds.size.width, 0)];
    }else{
        [self removeTimer];
        [self.collectionView setContentOffset:CGPointZero animated:NO];
        [self.collectionView reloadData];
    }
    
}


- (void)pageControlAction:(UIPageControl *)sender{
    if (self.urlArray.count >= 2) {
        [self nextImage];
    }
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.urlArray.count >= 2) {
        return 3;
    }
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.urlArray.count >= 2) {
        if (section == 1)return self.urlArray.count;
        return 1;
    }else{
        return self.urlArray.count;
    }
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    APPublicTimerDispalyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PublicTimerDispalyCell" forIndexPath:indexPath];
    
    if (indexPath.section == 1) {
        UIImage *image = [self _preHandleObject:self.urlArray[indexPath.item]];
        cell.imgView.image = image;

    }else if (indexPath.section == 0){
        UIImage *image = [self _preHandleObject:[self.urlArray lastObject]];
        cell.imgView.image = image;

    }else if (indexPath.section == 2){
        UIImage *image = [self _preHandleObject:[self.urlArray firstObject]];
        cell.imgView.image = image;
    }
    return cell;
}

- (UIImage *)_preHandleObject:(NSString *)imageName{
    if (_isLocalFile) {
        return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",images_path,imageName]];
    }else{
        return [UIImage imageNamed:imageName];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(publicTimerDisplayView:displayViewSelectedAtIndexPath:info:)]) {
        [self.delegate publicTimerDisplayView:self displayViewSelectedAtIndexPath:indexPath info:self.infoDictionary];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(nonnull UICollectionViewCell *)cell forItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (self.delegate && [self.delegate respondsToSelector:@selector(publicTimerDisplayView:displayViewEndDisplayAtIndexPath:)]) {
        [self.delegate publicTimerDisplayView:self displayViewEndDisplayAtIndexPath:indexPath];
    }
}

- (void)nextImage {
    if (self.urlArray.count <= 1) {
        return;
    }
    NSInteger page = self.pageControl.currentPage;
    if (page == self.urlArray.count - 1) {
        page = 0;
    }else{
        page++;
    }
    @try {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page inSection:1] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    } @catch (NSException *exception) {
    } @finally {
    }
}



#pragma mark -- scrollView delegate --
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        NSInteger page = (NSInteger)((scrollView.contentOffset.x - self.collectionView.bounds.size.width) / self.bounds.size.width);
        self.pageControl.currentPage = page;
    }

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat scrollviewW =  self.collectionView.frame.size.width;
    CGFloat x = scrollView.contentOffset.x - scrollviewW;
    NSInteger page = (x + scrollviewW/ 2) / scrollviewW;
    self.pageControl.currentPage = page;
    if (_urlArray.count > 1) {
        if (scrollView.contentOffset.x<= (scrollviewW * 0.5)) {
            [self.collectionView setContentOffset:CGPointMake(self.urlArray.count*scrollviewW, 0) animated:NO];
        }else if(scrollView.contentOffset.x>=(self.urlArray.count * scrollviewW + 0.5*scrollviewW)){
            [self.collectionView setContentOffset:CGPointMake(scrollviewW, 0) animated:NO];
        }
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (_isAutoScroll) {
        [self removeTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (_isAutoScroll) {
        if (!_timer) {
            [self addTimer];
        }
    }
}
- (void)addTimer{
    if (_timer || (_urlArray.count <= 1)) {
        return;
    }
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(3.0 * NSEC_PER_SEC);
    dispatch_source_set_timer(_timer, start, interval, 0);
    WS(ws);
    dispatch_source_set_event_handler(_timer, ^{
        [ws nextImage];
    });
    dispatch_resume(_timer);
}

- (void)removeTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)dealloc{
    [self removeTimer];
}
@end
